import { defineStore } from "pinia";
import {ref} from "vue"
import type { WordRecord } from "../types/WordResponse";
import { WordDaoFactory } from "../services/dao/WordDaoFactory";

export const useDictStore = defineStore("dict",()=>{

    const myDict = ref<Map<string,WordRecord>>(new Map())
    let wordDao = WordDaoFactory.getWordDao()


    /**
     * 没有查询过的 添加到缓存
     * 
     * 我的词典 查询是包含结果的，需要更多资料时才第二次http查询
     * 
     * 
     */

    // 保存已经查询过的
    // const cacheWords = ref<Map<string,WordRecord>>()

    const isKnownWord = (word:string) => {
        if(myDict.value==undefined) {
            console.log("mydict is null")
            return false
        }
        return myDict.value.has(word)&&myDict.value.get(word)?.star==3
    }
    const addMyWord = (word:string, star:number,translation:string,definition:string) => { 
        myDict.value.set(word,{
            word:word, 
            star:star,
            translation:translation,
            definition:definition
        })
    }
    async function fetchWords() {
        const response = await wordDao.getAllWords({
            page:1,
            limit:2000
        })
        for (let item of response) {
            myDict.value.set(item.word, item);
        }
        console.log("fetch word resut:",response)

    }

    return {
        myDict,
        addMyWord,
        isKnownWord,
        fetchWords,

    }
})